package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.LoginDTO;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.ex.CustomerException;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户业务层实现
 */
@Service
@Transactional
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 用户登录
     *
     * @param loginDTO
     * @param code
     * @return
     */
    @Override
    public long login(LoginDTO loginDTO, String code) {
        // 比较验证码
        if (StringUtils.isBlank(code)) {
            throw new CustomerException("验证码异常");
        }
        if (!code.equals(loginDTO.getCode())) {
            throw new CustomerException("验证码有误！");
        }
        // 登录：根据手机号查询
        User user = this.getOne(Wrappers.<User>lambdaQuery().eq(User::getPhone, loginDTO.getPhone()));

        // 没有用户：直接给你开通
        if (user == null) {
            user = new User();
            user.setPhone(loginDTO.getPhone());
            user.setStatus(1);
            this.save(user);
        }

        //登录
        return user.getId();
    }
}